package com.rickpan.repository;

import com.rickpan.entity.Tag;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Optional;

/**
 * 标签数据访问层
 * 
 * @author RickPan Team
 * @since 2024-01-06
 */
@Repository
public interface TagRepository extends JpaRepository<Tag, Long> {

    /**
     * 根据用户ID和类型查找标签
     */
    List<Tag> findByUserIdAndTypeOrderByUsageCountDescCreatedAtDesc(Long userId, String type);

    /**
     * 根据用户ID查找所有标签
     */
    List<Tag> findByUserIdOrderByTypeAscUsageCountDescCreatedAtDesc(Long userId);

    /**
     * 根据用户ID、名称和类型查找标签（用于重复检查）
     */
    Optional<Tag> findByUserIdAndNameAndType(Long userId, String name, String type);

    /**
     * 根据用户ID和标签ID查找标签
     */
    Optional<Tag> findByIdAndUserId(Long id, Long userId);

    /**
     * 根据用户ID和类型统计标签数量
     */
    long countByUserIdAndType(Long userId, String type);

    /**
     * 根据用户ID统计总标签数量
     */
    long countByUserId(Long userId);

    /**
     * 搜索标签
     */
    @Query("SELECT t FROM Tag t WHERE t.userId = :userId AND " +
           "(t.name LIKE %:keyword% OR t.type LIKE %:keyword%) " +
           "ORDER BY t.usageCount DESC, t.createdAt DESC")
    List<Tag> searchTags(@Param("userId") Long userId, @Param("keyword") String keyword);

    /**
     * 获取热门标签
     */
    @Query("SELECT t FROM Tag t WHERE t.userId = :userId AND t.usageCount > 0 " +
           "ORDER BY t.usageCount DESC, t.createdAt DESC")
    List<Tag> findPopularTags(@Param("userId") Long userId);
}
